#include <stdio.h>
#include <string.h>
#include "db_query.h"

/**
  * @brief  变量查询操作
  * @Notes  None
  * @param  dbsock, MySQL连接socket
  * @retval 0 成功
  			1 MySQL查询过程报错
  			2 MySQL结果集访问失败
  			3 结果集0行
  */
int QUERY_VAR(char* sql, struct __return_struct* retst,
					MYSQL* dbsock)
{
	int ret;
	int errno; int rst = mysql_real_query(dbsock, sql, (unsigned int)strlen(sql));
	if(rst){ 
		fprintf(stderr, "MySQL/> SELECT, {ERROR %d} %s\n", (errno = mysql_errno(dbsock)), mysql_error(dbsock)); 
		printf("%s\n", sql);
		ret = 1;
	}
	else{
		retst->_SET = mysql_store_result(dbsock);
		if(retst->_SET){
			retst->nRow = (unsigned long)mysql_num_rows(retst->_SET);
			retst->nCol = (unsigned long)mysql_num_fields(retst->_SET);
			//printf("Row: %d, Col: %d\n", retst->nRow, retst->nCol);
			if(retst->nRow > 0){
				MYSQL_ROW _ROW_SET; int i;
				retst->ValMat = (char**)malloc(sizeof(char*) * (retst->nRow*retst->nCol));
				for(i = 0; i < retst->nRow*retst->nCol; i++)
				{
					retst->ValMat[i] = (char*)malloc(sizeof(char) * 300);
				}
				int r = 0; int c;
				while((_ROW_SET = mysql_fetch_row(retst->_SET)) != NULL)
				{
					for(c = 0; c < retst->nCol; c++)
					{
						strcpy(retst->ValMat[r*retst->nCol + c], _ROW_SET[c]);
					}
					mysql_data_seek(retst->_SET, ++r);
				}
			}
			else{
				/* 避免VAR_FREE函数中free发生错误导致程序退出 */
				retst->ValMat = NULL;
				ret = 3;
			}
			mysql_free_result(retst->_SET);
		}
		else
			ret = 2;
	}
	return ret;
}

char* VARVAL(struct __return_struct retst, int Row, int Col)
{
	if(retst.nRow > 0)
		return retst.ValMat[Row*retst.nCol + Col];
	else
		return NULL;
}

void QUERY_VAR_FREE(struct __return_struct* retst)
{
	int i;
	for(i = 0; i < retst->nRow*retst->nCol; i++)
	{
		if(retst->ValMat[i] != NULL)
			free(retst->ValMat[i]);
	}
	if(retst->ValMat != NULL)
		free(retst->ValMat);
}